<?php

namespace App\Exception\Handler;

use App\Common\Librarys\ApiResponse;
use App\Constants\ErrorCode;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Utils\Codec\Json;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class ValidationException extends ExceptionHandler
{
    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        $this->stopPropagation();
        $message = $throwable->validator->errors()->first();
        $body = json_encode([
            'errorCode' => $throwable->getCode(),
            'data' => [],
            'message' => $message,
        ], JSON_UNESCAPED_UNICODE);
        return $response->withStatus(500)
            ->withAddedHeader('content-type', 'application/json; charset=utf-8')
            ->withBody(new SwooleStream($body));
    }

    public function isValid(Throwable $throwable): bool
    {
        var_dump($throwable instanceof \Hyperf\Validation\ValidationException);
        return $throwable instanceof \Hyperf\Validation\ValidationException;
    }
}